/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package message;

import entity.PlainTextMessage; 
import javax.annotation.Resource; 
import javax.ejb.ActivationConfigProperty; 
import javax.ejb.MessageDriven; 
import javax.ejb.MessageDrivenContext; 
import javax.jms.JMSException; 
import javax.jms.Message; 
import javax.jms.MessageListener; 
import javax.jms.TextMessage; 
import javax.persistence.EntityManager; 
import javax.persistence.PersistenceContext; 
/**
 *
 * @author Vincent
 */
@MessageDriven(mappedName = "jms/queueMessageMe", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class MessageMe implements MessageListener {
    @Resource 
    private MessageDrivenContext messageDrivenContext; 
     
    @PersistenceContext  
    private EntityManager entityManager; 
    
    public MessageMe() {
    }
    
    @Override
    public void onMessage(Message message) {
        TextMessage textMessage = null; 
 
        try  
        { 
            if (message instanceof TextMessage)  
            { 
                textMessage = (TextMessage) message; 
                String temp = textMessage.getText();
                String[] data = temp.split("\\|", 5);
                
                String sender = data[0];
                String receiver = data[1];
                String msgDate = data[2];
                String title = data[3];
                String msg = data[4];
                
                PlainTextMessage plainTextMessage = new PlainTextMessage(); 
                plainTextMessage.setMessage(msg);
                plainTextMessage.setSender(sender);
                plainTextMessage.setReceiver(receiver);
                plainTextMessage.setTitle(title);
                plainTextMessage.setIsRead(false);
                plainTextMessage.setMessageDate(msgDate);
                //get receiver id and sender id
                entityManager.persist(plainTextMessage); 
                 
                System.out.println("********** MessageMe: Message received and saved: " + textMessage.getText()); 
            } 
            else  
            {    
                System.out.println("********** MessageMe: Message received has wrong type."); 
            } 
        } 
        catch (JMSException jmsEx)  
        { 
            jmsEx.printStackTrace(); 
            messageDrivenContext.setRollbackOnly(); 
        } 
        catch (Exception ex)  
        { 
            ex.printStackTrace(); 
        } 
    }
}
